<?php
class AnalyzedMessage {
    public $content;
    public $words;

    public function  __construct($content) {
        $this->content = strtolower($content);
        $words = array();

        foreach(explode(' ', preg_replace('/[^a-z\x{105}\x{119}\x{F3}\x{15B}\x{142}\x{17C}\x{17A}\x{144}\x{107}\'/iu')) as $word) {
            $len = strlen($word);
            if($len > 3 && $len <= 25) {
                $words[] = $word;
            }
        }
        
        $this->words = $words;
    }
}

interface SpamAnalysisTechnique {
    public function analyze(AnalyzedMessage $message);
}

class BayesTechnique implements SpamAnalysisTechnique {
    private $controller;

    public function __construct($controller) {
        $this->controller = $controller;
        $this->controller->loadModel('SpamBayesEntry');
    }

    public function analyze(AnalyzedMessage $message) {
        $query_words = array();
        $i = 0;
        foreach($message->words as $word) {
            if($i > 0) {
                $query_words .= ',';
            }
            $query_words .= "'".$word."'";
            $i++;
        }
        $data = $this->controller->SpamBayesEntry->find('all', array(
            'conditions' => array('SpamBayesEntry.word in ('.$query_words.')'),
            'fields' => array('sum(SpamBayesEntry.log) as SpamBayesEntry.spam_weight')
        ));
        print_r($data);
    }
}

class StandaloneAntispamFilterComponent extends Object {
    private $controller;
    private $techniques = array();


    public function initialize(&$controller, $settings) {
        $this->controller = $controller;

        $this->techniques[] = new BayesTechnique($this->controller);
    }

    public function isSpam($message) {
        $message = new AnalyzedMessage($message);

        $sum = 0;
        foreach($this->techniques as $technique) {
            $sum += $technique->analyze($message);
        }

        return ($sum < 0);

    }
}
?>
